package com.tkc.common.util;

import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * 
 * @Function: json格式数据处理工具类
 * 
 * @Project :assessmenttask 
 * @Package :com.tkc.common.util 
 * @File :JsonUtil.java 
 * @ClassName: JsonUtil  
 * 
 * @author tankaichao 
 * @email cgztkc@126.com 
 * @Date 2016年8月9日下午7:06:01
 * @since JDK 1.8 
 *
 */
public final class JsonUtil {
    /**
     * 默认实例
     */
    public static final ObjectMapper INSTANCE;
    /**
     * PascalCase实例
     */
    public static final ObjectMapper PASCAL_CASE_INSTANCE;

    public static final ObjectMapper DB_EXTENSION_INSTANCE;

    static {
        INSTANCE = new ObjectMapper();
        INSTANCE.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        PASCAL_CASE_INSTANCE = new ObjectMapper();
        PASCAL_CASE_INSTANCE
            .setPropertyNamingStrategy(new PropertyNamingStrategy.PropertyNamingStrategyBase() {
                /**  */
                private static final long serialVersionUID = 1766624727188140566L;

                @Override
                public String translate(final String propertyName) {
                    // "camelCase" to "PascalCase"
                    return StringUtils.capitalize(propertyName);
                }
            });

        DB_EXTENSION_INSTANCE = new ObjectMapper();
        DB_EXTENSION_INSTANCE.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        DB_EXTENSION_INSTANCE.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
        DB_EXTENSION_INSTANCE.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
        DB_EXTENSION_INSTANCE.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        DB_EXTENSION_INSTANCE.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
        DB_EXTENSION_INSTANCE.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    }
    
    public static void responseOutWithJson(ServletResponse response,  
			Object result){
		JSONObject responseJSONObject = JSONObject.fromObject(result);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8"); 
		PrintWriter out = null;
		try {  
	        out = response.getWriter();  
	        out.append(responseJSONObject.toString());  
	    } catch (IOException e) {  
	        e.printStackTrace();  
	    } finally {  
	        if (out != null) {  
	            out.close();  
	        }  
	    }  
	}
    
}